package cn.vc.auth.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.vc.auth.entity.po.VUser;
import cn.vc.basicmodule.entity.Result;
import cn.vc.auth.entity.po.AuthorityLevel;
import cn.vc.auth.service.CaptchaService;
import cn.vc.auth.service.UserService;
import cn.vc.wallet.feign.clients.WalletClient;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录服务接口
 */
@Slf4j
@RestController
//@RequestMapping("/login")
public class LogInController {
    @Autowired
    private UserService userService;
    @Autowired
    private CaptchaService captchaService;
    @Autowired
    private HttpSession session;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private WalletClient walletClient;


    /**
     * <h2>登录</h2>
     * @param account
     * @param password
     * @return
     */
    @PostMapping("/login")
    public Result<?> logIn(HttpServletResponse response, @RequestParam("account") String account, @RequestParam("password") String password) {
        log.info("登录：{}", account);
        log.info("===");
        VUser VUser = userService.selectByAccountAndPassword(account, password, false);
        log.info("<<{}", account);
        // 查不到可能是邮箱登录
        if (VUser ==null) {
            VUser = userService.selectByEmailAndPassword(account, password);
        }
        log.info(">>{}", password);
//        String token = null;//用户登录令牌
        if (VUser !=null) {
            StpUtil.login(VUser.getId(), 60 * 60);
            StpUtil.getSession().set("user", VUser);
//            stringRedisTemplate.opsForValue().set(token, JSON.toJSONString(VUser), 60, TimeUnit.MINUTES);
//            System.out.println(stringRedisTemplate.opsForValue().get(token));
            //创建Cookie对象
//            Cookie c_token = new Cookie("token", token);
            //设置存活时间
//            int time = 60*60;//1小时
//            c_token.setMaxAge(time);
            //发送cookie
//            response.addCookie(c_token);
        }
        log.info("登录：{}", VUser);
//        return new Result<>(VUser != null?1:0, token);
        return new Result<>(VUser != null?1:0);
    }

    /**
     * 注册
     */
    @PostMapping
    public Result<VUser> signIn(@RequestParam("captcha") String captcha, @RequestBody VUser vUser) {
        if (captchaService.comparisonCaptcha(CaptchaService.prefixType.signIn.getValue()+"_"+ vUser.getEmail(), captcha)) {
            boolean bo = userService.insert(vUser);
            // 创建用户成功
            if (bo) {
                // 创建用户钱包
                walletClient.createWallet(vUser.getId());
                return new Result<>(1, vUser);
            } else {
                return new Result<>(0);
            }
        } else {
            return new Result<>(0);
        }
    }



    /**
     * 登出
     * @param response
     */
//    @RequestMapping("/logout")
//    public Result<?> logOut(HttpServletResponse response, @RequestHeader("token") String token) {
//        String userJson = stringRedisTemplate.opsForValue().get(token);
//        //用户未登录
//        if (userJson==null) return new Result<>(0);
//        VUser myVUser =  JSON.parseObject(userJson, VUser.class);
//        //清除session域中的数据
//        session.invalidate();
//        //创建Cookie对象
//        Cookie c_token = new Cookie("token", "");
//        //设置存活时间
//        c_token.setMaxAge(0);
//        //发送cookie
//        response.addCookie(c_token);
//        //记录日志
//        log.info("退出登录："+ myVUser);
//        return new Result<>(1);
//    }
    @RequestMapping("/logout")
    public Result<?> logOut(HttpServletResponse response) {
        StpUtil.logout();
        //清除session域中的数据
        session.invalidate();
        //创建Cookie对象
        Cookie c_token = new Cookie("token", "");
        //设置存活时间
        c_token.setMaxAge(0);
        //发送cookie
        response.addCookie(c_token);
        //记录日志
        log.info("退出登录：");
        return new Result<>(1);
    }



    /**
     * 查询登录及用户信息
     */
    @GetMapping("/{token}")
//    @PreAuthorize("hasAuthority('ordinary')")
    public Result<?> selectMy(@PathVariable("token") String token) {
        Object userJSON = stringRedisTemplate.opsForValue().get(token);
        if (userJSON==null) return new Result<>(0, null);
        VUser myVUser = JSON.parseObject(userJSON.toString(), VUser.class);
        return new Result<>(1, myVUser);
    }

    /**
     * 查询用户信息
     * @param id
     */
    @GetMapping("/login/user/{id}")
    public Result<VUser> selectById(@PathVariable Long id) {
        VUser VUser = userService.selectById(id, AuthorityLevel.TOURIST);
        return new Result<>(1, VUser);
    }



    /**
     * 忘记密码
     * @param email 电子邮箱
     * @param captcha 验证码
     * @param newPassword 新密码
     */
    @PutMapping("/forgot")
    public Result<?> forgotPassword(@RequestParam("email") String email, @RequestParam("captcha") String captcha, @RequestParam("newPassword") String newPassword) {
        boolean bo = captchaService.comparisonCaptcha(CaptchaService.prefixType.forgot.getValue()+"_"+email, captcha);
        VUser VUser = userService.selectByEmail(email);
        bo = userService.updatePassword(VUser.getAccount(), VUser.getPassword(), newPassword);
        log.info("忘记密码："+bo);
        return new Result<>(bo);
    }
}
